package com.globalwave.db.seq.impl;

import java.sql.PreparedStatement;

import com.globalwave.db.exception.DBException;
import com.globalwave.db.seq.Sequence;

public class DatabaseSequence extends BaseSequence implements Sequence {

	private String name_ ;
	
	public DatabaseSequence(String name) {
		this.name_ = name ;
	}
	
	@Override
	public long currentVal() {
		return getLong("select " + name_ + ".currval from dual");
	}

	@Override
	public long nextVal() {
		return getLong("select " + name_ + ".nextval from dual");
	}


	@Override
	public long create() {

		PreparedStatement ps = null ;
		try {
			getConnection().setAutoCommit(false) ;

		    ps = getConnection().prepareStatement("create sequence " + name_) ;
		    
		    getConnection().commit() ;
		} catch (Exception e) {
		    try {
				getConnection().rollback();
			} catch (Exception e1) {
				throw new DBException(e1) ;
			}
			throw new DBException(e) ;
		} finally {
			if (ps != null) {
				try {
					ps.close() ;
				} catch (Exception e) {
					throw new DBException(e) ;
				}
			}
		}
		
		return nextVal() ;
	}
}
